package com.java.star.mall.front.util;

import com.java.star.mall.common.exception.BusinessException;
import com.java.star.mall.common.response.StatusCode;
import com.java.star.mall.front.pojo.authentication.CurrentPrincipal;

/**
 * 当前登录用户的工具类
 */
public class CurrentPrincipalUtils {

    //用于用户对象的快速传输
    private static ThreadLocal<CurrentPrincipal> currentPrincipalThreadLocal = new ThreadLocal<>();

    /**
     * 设置当事人对象
     *
     * @param currentPrincipal 当前用户
     */
    public static void setCurrentPrincipal(CurrentPrincipal currentPrincipal) {
        if (currentPrincipal != null) {
            currentPrincipalThreadLocal.set(currentPrincipal);
        }
    }

    /**
     * 获取当事人对象
     */
    public static CurrentPrincipal getCurrentPrincipal() {
        CurrentPrincipal currentPrincipal = currentPrincipalThreadLocal.get();
        if (currentPrincipal == null) {
            throw new BusinessException(StatusCode.JWT_UNAUTHORIZED_ERROR);
        }
        return currentPrincipal;
    }

    /**
     * 删除当事人对象
     */
    public static void removeCurrentPrincipal() {
        currentPrincipalThreadLocal.remove();
    }
}
